/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { ApiAttr, ApiDeviceGroup, ApiSensorGroup } from "_common/api/iot";
import { DrawerProps } from "_common/DataType";
import { IotAttr, IotDeviceGroup, IotSensorGroup } from "_common/entity";
import { AxiosInstance } from "axios";
import React, { useState, useEffect, useRef } from "react";
import {
  Button,
  Divider,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
  Select,
} from "tdesign-react";
import FormItem from "tdesign-react/es/form/FormItem";
type ProductDrawerProps = DrawerProps & {
  axios: AxiosInstance;
};
const ProductDrawer: React.FC<ProductDrawerProps> = (
  props: ProductDrawerProps
) => {
  const { open, axios, edit, onSuccess, value } = props;
  const formRef = useRef<FormInstanceFunctions>();

  // 列表状态
  const [attrList, setAttrList] = useState<IotAttr[]>([]);
  const [sensorGroupList, setSensorGroupList] = useState<IotSensorGroup[]>([]);

  const apiAttr = new ApiAttr(axios);
  const apiProduct = new ApiDeviceGroup(axios);
  const apiSensorGroup = new ApiSensorGroup(axios);

  useEffect(() => {
    return () => {
      formRef.current?.reset();
    };
  }, []);

  useEffect(() => {
    getAttrList();
    getSensorGroupList();
    if (value && edit) {
      formRef.current?.setFieldsValue(value);
    }
  }, [edit, value]);

  const handleClose = () => {
    onSuccess?.(false);
    formRef.current?.reset();
  };

  // 获取属性列表
  const getAttrList = async () => {
    const response = await apiAttr.getAttrList();
    if (response && response.code == 200 && response.data) {
      setAttrList(response.data);
    }
  };
  // 获取物模型类型列表
  const getSensorGroupList = async () => {
    const response = await apiSensorGroup.getSensorGroupList();
    if (response && response.code == 200 && response.data) {
      setSensorGroupList(response.data);
    }
  };

  // 新增分组
  const createProduct = async (data: IotDeviceGroup) => {
    const response = await apiProduct.createDeviceGroup(data);
    if (response && response.code == 200 && response.data) {
      handleClose();
    }
  };
  // 更新分组
  const updateProduct = async (data: IotDeviceGroup) => {
    const response = await apiProduct.updateDeviceGroup({
      ...data,
      id: value?.id,
    });
    if (response && response.code == 200 && response.data) {
      handleClose();
    }
  };

  return (
    <Drawer
      header={`${edit ? "编辑" : "添加"}产品`}
      footer={false}
      visible={open}
      sizeDraggable
      size="medium"
      onClose={handleClose}
    >
      <Form
        ref={formRef}
        labelWidth={100}
        onSubmit={async (data) => {
          // 是否校验通过
          if ((await formRef.current?.validateOnly()) == true) {
            edit
              ? updateProduct(data.fields as IotDeviceGroup)
              : createProduct(data.fields as IotDeviceGroup);
          }
        }}
      >
        <FormItem
          label="产品名称"
          rules={[{ required: true }]}
          name="groupName"
        >
          <Input />
        </FormItem>
        <FormItem
          label="产品编码"
          rules={[{ required: true }]}
          name="groupCode"
        >
          <Input />
        </FormItem>
        <FormItem
          label="产品描述"
          rules={[{ required: false }]}
          name="groupDesc"
        >
          <Input />
        </FormItem>
        <Divider layout="horizontal" content="附属信息" />
        <FormItem label="关联属性" rules={[{ required: false }]} name="attrIds">
          <Select multiple placeholder="请选择关联属性">
            {attrList.map((item) => (
              <Select.Option key={item.id} value={item.id}>
                {item.attrName}
              </Select.Option>
            ))}
          </Select>
        </FormItem>
        <FormItem
          label="物模型"
          rules={[{ required: false }]}
          name="sensorGroupIds"
        >
          <Select multiple placeholder="请选择绑定物模型">
            {sensorGroupList.map((item) => (
              <Select.Option key={item.id} value={item.id}>
                {item.groupName}
              </Select.Option>
            ))}
          </Select>
        </FormItem>
        <FormItem className="float-right">
          <Button type="submit" theme="primary">
            提交
          </Button>
          <Button type="reset" theme="success" style={{ marginLeft: 12 }}>
            重置
          </Button>
        </FormItem>
      </Form>
    </Drawer>
  );
};
export default ProductDrawer;
